package com.example.infrastructure;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class FileService {

	@Autowired
	private Path audioStoragePath;

	public String readFile(String fileName) {
		try {
			ClassPathResource resource = new ClassPathResource(fileName);
			InputStream inputStream = resource.getInputStream();
			String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
			System.out.println(content);
			inputStream.close();
			return content;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return StringUtils.EMPTY;
	}

	public Path saveFile(MultipartFile audioFile) {
		Path tempFile = null;
		try {
			// 生成唯一的文件名
			String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
			String uniqueId = UUID.randomUUID().toString().substring(0, 8);
			String fileName = String.format("audio_%s_%s.wav", timestamp, uniqueId);
			tempFile = audioStoragePath.resolve(fileName);

			// 保存音频文件
			Files.copy(audioFile.getInputStream(), tempFile);
			return tempFile;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public void deleteFile(Path tempFile) {

		// 清理临时文件
		if (tempFile != null) {
			try {
				Files.deleteIfExists(tempFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
